//
//  labelRecommendDetailViewController.m
//  Wedding fantastic
//
//  Created by dllo on 15/7/9.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "labelRecommendDetailViewController.h"
#import "labelRecommendDetailModel.h"
#import "CCSegmentedControl.h"

@interface labelRecommendDetailViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
// 套餐集合视图
@property (nonatomic, retain) UICollectionView *packageCollectionView;
// 套餐信息数组
@property (nonatomic, retain) NSMutableArray *packageInfoArr;
// 背景scroll
@property (nonatomic, retain) UIScrollView *backgroundScroll;
// 案例集合视图
@property (nonatomic, retain) UICollectionView *caseCollectionVeiw;
// 案例信息数组
@property (nonatomic, retain)NSMutableArray *caseInfoArr;
// 分块控制器
@property (nonatomic, retain)CCSegmentedControl *segmentedControl;
// 套餐新地址
@property (nonatomic, copy)NSString *packageUrlStr;
// 案例新地址
@property (nonatomic, copy)NSString *caseUrlStr;
@end

@implementation labelRecommendDetailViewController
- (void)dealloc {
    [_backgroundScroll release];
    [_ID release];
    [_packageCollectionView release];
    [_caseCollectionVeiw release];
    [_caseInfoArr release];
    [_packageInfoArr release];
    [_segmentedControl release];
    [_packageUrlStr release];
    [_caseUrlStr release];
    [_detaiTitle release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.packageInfoArr = [NSMutableArray array];
        self.caseInfoArr = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    
    

    
    // 解析套餐数据
    [self createDataPackage];
    // 解析案例数据
    [self createDataCase];
    
    

    
    
    // 视图
    [self createView];
    
    self.page = 1;
    //网络请求
    [self addHeader];
    [self addFooter];
    
    // 回到顶部button
    UIButton *topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    topButton.frame = CGRectMake(300 * kWidth / 375, 450 * kHeight / 667, 35 * kWidth / 375, 38 * kHeight / 667);
    [topButton setBackgroundImage:[UIImage imageNamed:@"backTop"] forState:UIControlStateNormal];
    topButton.alpha = 0.6;
    [self.view addSubview:topButton];
    [topButton addTarget:self action:@selector(topAction:) forControlEvents:UIControlEventTouchUpInside];
}
// 回到顶部
- (void)topAction:(UIButton *)button {
    [self.packageCollectionView setContentOffset:CGPointZero animated:YES];
    [self.caseCollectionVeiw setContentOffset:CGPointZero animated:YES];
}

//
- (void)addHeader
{
    __block labelRecommendDetailViewController *detailVC = self;
    
    // 添加下拉刷新头部控件
    [self.packageCollectionView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        detailVC.page = 1;
        detailVC.Loading = NO;//标记为下拉操作
        [self reCreateData];//重新请求数据
        
    }];
    [self.caseCollectionVeiw addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        detailVC.page = 1;
        detailVC.Loading = NO;//标记为下拉操作
        [self reCreateData];//重新请求数据
        
    }];
#pragma mark 自动刷新(一进入程序就下拉刷新)
    
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    __block labelRecommendDetailViewController *detailVC = self;
    // 添加上拉刷新尾部控件
    [self.packageCollectionView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        detailVC.Loading = YES;//标记为上拉操作
        [detailVC reCreateData];//请求更多数据
        
    }];
    [self.caseCollectionVeiw addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        detailVC.Loading = YES;//标记为上拉操作
        [detailVC reCreateData];//请求更多数据
        
    }];
}
-(void)reCreateData

{
    /**
     *  套餐加载
     */
    NSString *url = @"http://www.hunliji.com/p/wedding/index.php/home/APIMerchant/WorkList?city=0&sort%5Bkey%5D=created_at&sort%5Border%5D=null&commodity_type=0&mark=999999&per_page=20&page=nnnnnn";

    NSString *pageSStr = [NSString stringWithFormat:@"%ld", ++self.page];


    NSString *urlStr = [url stringByReplacingOccurrencesOfString:@"nnnnnn" withString:pageSStr];
    if (self.index == 0 || self.index == 5) {
        
        // 替换
        self.packageUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
    } else {
        
        self.packageUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"created_at" withString:@"default"];
        self.packageUrlStr = [self.packageUrlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
        self.packageUrlStr = [self.packageUrlStr stringByReplacingOccurrencesOfString:@"null" withString:@"desc"];
    }
    
    [NetworkTool get:self.packageUrlStr body:nil httpResult:JSON success:^(id result) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.packageCollectionView animated:YES];
        [hub show:YES];
        // 如果成功返回数据
        // 接收数据
        NSDictionary *resultDic = result;
        
        NSArray *worksArr = resultDic[@"works"];
        for (NSDictionary *tempDic in worksArr) {
            labelRecommendDetailModel *model = [[labelRecommendDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.packageInfoArr addObject:model];
            
            
        }
        
        [self.packageCollectionView headerEndRefreshing];
        [self.packageCollectionView footerEndRefreshing];
        
        [self.packageCollectionView reloadData];
        
        //        NSLog(@"gggg%ld", self.packageInfoArr.count);
        // 数据加载成功之后,隐藏小菊花
        [hub hide:YES];
    } failure:^(NSError *error) {
        
    }];
    
    
    
    
    
    /**
     *  加载案例
     */
    NSString *urlCase = @"http://www.hunliji.com/p/wedding/index.php/home/APIMerchant/WorkList?city=0&sort%5Bkey%5D=created_at&sort%5Border%5D=null&commodity_type=1&mark=999999&per_page=20&page=cccccc";
    NSString *pageSStrCse = [NSString stringWithFormat:@"%ld", ++self.page];
    NSString *urlStrCase = [urlCase stringByReplacingOccurrencesOfString:@"cccccc" withString:pageSStrCse];
    
    if (self.index == 0 || self.index == 5) {
        
        // 替换
        self.caseUrlStr = [urlStrCase stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
    } else {
        
        self.caseUrlStr = [urlStrCase stringByReplacingOccurrencesOfString:@"created_at" withString:@"default"];
        self.caseUrlStr = [self.caseUrlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
        self.caseUrlStr = [self.caseUrlStr stringByReplacingOccurrencesOfString:@"null" withString:@"desc"];
    }
    
    [NetworkTool get:self.caseUrlStr body:nil httpResult:JSON success:^(id result) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.caseCollectionVeiw animated:YES];
        [hub show:YES];
        // 如果成功返回数据
        // 接收数据
        NSDictionary *resultDic = result;
        
        NSArray *worksArr = resultDic[@"works"];
        for (NSDictionary *tempDic in worksArr) {
            labelRecommendDetailModel *model = [[labelRecommendDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            
            [self.caseInfoArr addObject:model];
        }
        
        if (self.page == 3) {
            self.caseCollectionVeiw.footerHidden = YES;
        }
        
        
        [self.caseCollectionVeiw headerEndRefreshing];
        [self.caseCollectionVeiw footerEndRefreshing];
        [self.caseCollectionVeiw reloadData];
        //        NSLog(@"gggg%ld", self.packageInfoArr.count);
        // 数据加载成功之后,隐藏小菊花
        [hub hide:YES];
        
    } failure:^(NSError *error) {
        
    }];

}

// segment触发方法
- (void)clickSeg:(UISegmentedControl *)seg {
    switch (seg.selectedSegmentIndex) {
        case 0:
            self.backgroundScroll.contentOffset = CGPointMake(0, 0);
            seg.selectedSegmentIndex = 0;
            break;
            
        default:
            self.backgroundScroll.contentOffset = CGPointMake(kWidth, 0);
            seg.selectedSegmentIndex = 1;
            break;
    }
}
// scroller结束拖拽时触发, 只有不动了才会触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 判断segment当前是谁
    if (self.backgroundScroll.contentOffset.x < kWidth ) {
        self.segmentedControl.selectedSegmentIndex = 0;
    } else {
        self.segmentedControl.selectedSegmentIndex = 1;
    }
}
//
- (void)createView {
    // 重新设置title
    self.title = self.detaiTitle;
    
    // segment
    self.segmentedControl = [[CCSegmentedControl alloc] initWithItems:@[@"套餐", @"案例"]];
    self.segmentedControl.frame = CGRectMake(0, 0, kWidth, 50 * kHeight / 667);
    
    //设置背景图片，或者设置颜色，或者使用默认白色外观
//    self.segmentedControl.backgroundImage = [UIImage imageNamed:@"segment_bg.png"];
    self.segmentedControl.backgroundColor = [UIColor whiteColor];
    
    //阴影部分图片，不设置使用默认椭圆外观的stain
    self.segmentedControl.selectedStainView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"stain.png"]];
//    self.segmentedControl = [[CCSegmentedControl alloc] init];
    self.segmentedControl.selectedStainView = [[UIImageView alloc] init];
    self.segmentedControl.selectedSegmentTextColor = [UIColor brownColor];
    self.segmentedControl.segmentTextColor = [self colorWithHexString:@"#535353"];
    [self.segmentedControl addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
    // 设置当前部分控件被选中
    self.segmentedControl.selectedSegmentIndex = 0;
    // 给seg添加出触发方法
    [self.segmentedControl addTarget:self action:@selector(clickSeg:) forControlEvents:UIControlEventValueChanged];
    
    
    // 背景scroll
    self.backgroundScroll = [[UIScrollView alloc] initWithFrame: CGRectMake(0, 50 * kHeight / 667, kWidth, kHeight - (50 + 64 + 49) * kHeight / 667)];
    [self.view addSubview:self.backgroundScroll];
    self.backgroundScroll.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
    self.backgroundScroll.delegate = self;
    // 按页滚动
    self.backgroundScroll.pagingEnabled = YES;
    // 滚动范围
    self.backgroundScroll.contentSize = CGSizeMake(kWidth * 2, 0);
    [self.backgroundScroll release];
    
    // 套餐集合视图
    // 1.集合布局
    UICollectionViewFlowLayout *packageFlowLayout = [UICollectionViewFlowLayout alloc];
    // 2. 设置每个item的大小(cell)
    packageFlowLayout.itemSize = CGSizeMake(kWidth - 20 * kWidth / 375, 300 * kWidth / 375);
    // 3.section中cell的边界范围
    // 取代上面的间距行
    packageFlowLayout.sectionInset = UIEdgeInsetsMake(10 * kWidth / 375, 10 * kHeight / 667, 10 * kWidth / 375, 10 * kHeight / 667);
    // 4.设置滑动方向
    packageFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 5. 集合视图
    self.packageCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - (50 + 49 + 64) * kHeight / 667) collectionViewLayout:packageFlowLayout];
    self.packageCollectionView.backgroundColor = [UIColor whiteColor];
    // 6.设置代理, 设置数据源
    self.packageCollectionView.delegate = self;
    self.packageCollectionView.dataSource = self;
    // 7.把集合视图添加到backgroundScroll上
    [self.backgroundScroll addSubview:self.packageCollectionView];
    // 8.内存管理
    [self.packageCollectionView release];
    // 9.注册
    // 第一个参数: 需要制定注册类型那个
    // 第二个参数: 重用标志
    [self.packageCollectionView registerClass:[packageCell class] forCellWithReuseIdentifier:@"reusePackage"];
    
    
    // 案例结合视图
    // 1.集合布局
    UICollectionViewFlowLayout *caseFlowLayout = [UICollectionViewFlowLayout alloc];
    // 2. 设置每个item的大小(cell)
    caseFlowLayout.itemSize = CGSizeMake(kWidth - 20 * kWidth / 375, 300 * kWidth / 375);
    // 3.section中cell的边界范围
    // 取代上面的间距行
    caseFlowLayout.sectionInset = UIEdgeInsetsMake(10 * kWidth / 375, 10 * kHeight / 667, 10 * kWidth / 375, 10 * kHeight / 667);
    // 4.设置滑动方向
    caseFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 5. 集合视图
    self.caseCollectionVeiw = [[UICollectionView alloc] initWithFrame:CGRectMake(kWidth, 0, kWidth, kHeight - (50 + 49 + 64) * kHeight / 667) collectionViewLayout:caseFlowLayout];
    self.caseCollectionVeiw.backgroundColor = [UIColor whiteColor];
    // 6.设置代理, 设置数据源
    self.caseCollectionVeiw.delegate = self;
    self.caseCollectionVeiw.dataSource = self;
    // 7.把集合视图添加到backgroundScroll上
    [self.backgroundScroll addSubview:self.caseCollectionVeiw];
    // 8.内存管理
    [self.caseCollectionVeiw release];
    // 9.注册
    // 第一个参数: 需要制定注册类型那个
    // 第二个参数: 重用标志
    [self.caseCollectionVeiw registerClass:[caseCell class] forCellWithReuseIdentifier:@"reuseCase"];
}
// 集合视图方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.packageInfoArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.packageCollectionView]) {
        packageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reusePackage" forIndexPath:indexPath];
        
        // 获取数据
        labelRecommendDetailModel *model = self.packageInfoArr[indexPath.row];
        cell.myImageView.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
        // 把图片赋给cell
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_path]];
        // 超值折扣对应信息的label
        // 标题标签
        //        cell.titleLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *discountTitleStr = model.title;
        cell.titleLabel.text = [NSString stringWithFormat:@" %@", discountTitleStr];
        // 市场价标签
        
        cell.market_priceLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *marketPriceStr = model.market_price;
        //
        cell.market_priceLabel.text = [NSString stringWithFormat:@"  市场价:%@元", marketPriceStr];
        // 设置字体
        cell.market_priceLabel.font = [UIFont systemFontOfSize:12];
        // 设置字体颜色
        cell.market_priceLabel.textColor = [UIColor grayColor];
        
        
        // 实际价格标签
        
        cell.actual_priceLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *actualPrice = model.actual_price;
        cell.actual_priceLabel.text = [NSString stringWithFormat:@"          现价:%@元", actualPrice];
        // 设置字体颜色
        cell.actual_priceLabel.textColor = [UIColor redColor];
        return cell;

    } else {
        caseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuseCase" forIndexPath:indexPath];
        
        // 获取数据
        labelRecommendDetailModel *model = self.caseInfoArr[indexPath.row];
        cell.myImageView.backgroundColor = [UIColor colorWithRed:241 / 255.0 green:241 / 255.0 blue:240 / 255.0 alpha:1];
        // 把图片赋给cell
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_path]];
        // 超值折扣对应信息的label
        // 标题标签
        //        cell.titleLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *discountTitleStr = model.title;
        cell.titleLabel.text = [NSString stringWithFormat:@" %@", discountTitleStr];
        // 市场价标签
        
        cell.market_priceLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *marketPriceStr = model.market_price;
        //
        cell.market_priceLabel.text = [NSString stringWithFormat:@"  市场价:%@元", marketPriceStr];
        // 设置字体
        cell.market_priceLabel.font = [UIFont systemFontOfSize:12];
        // 设置字体颜色
        cell.market_priceLabel.textColor = [UIColor grayColor];
        
        
        // 实际价格标签
        
        cell.actual_priceLabel.backgroundColor = [UIColor whiteColor];
        // 添加数据
        NSString *actualPrice = model.actual_price;
        cell.actual_priceLabel.text = [NSString stringWithFormat:@"          现价:%@元", actualPrice];
        // 设置字体颜色
        cell.actual_priceLabel.textColor = [UIColor redColor];
        return cell;

    }
}
//
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if ([collectionView isEqual:self.caseCollectionVeiw]) {
        discountModel *model = self.caseInfoArr[indexPath.row];
        
        recommendWorksDetailViewController *recommendWorkDVC = [[recommendWorksDetailViewController alloc] init];
        // 传id
        recommendWorkDVC.bID = (NSString *)model.id;
        
        [self.navigationController pushViewController:recommendWorkDVC animated:YES];
        [recommendWorkDVC release];
    } else {
        discountModel *model = self.packageInfoArr[indexPath.row];
        discountDetailViewController *discountDVC = [discountDetailViewController alloc];
        // 传id
        discountDVC.ID = (NSString *)model.id;
        [self.navigationController pushViewController:discountDVC animated:YES];
        [discountDVC release];
    }
}
// 解析套餐数据
- (void)createDataPackage {
//    NSString *key = @"created_at";

    NSString *urlStr = @"http://www.hunliji.com/p/wedding/index.php/home/APIMerchant/WorkList?city=0&sort%5Bkey%5D=created_at&sort%5Border%5D=null&commodity_type=0&mark=999999&per_page=20&page=1";

    if (self.index == 0 || self.index == 5) {
        
        // 替换
        self.packageUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
    } else {
        
        self.packageUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"created_at" withString:@"default"];
        self.packageUrlStr = [self.packageUrlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
        self.packageUrlStr = [self.packageUrlStr stringByReplacingOccurrencesOfString:@"null" withString:@"desc"];
    }
    
    [NetworkTool get:self.packageUrlStr body:nil httpResult:JSON success:^(id result) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.packageCollectionView animated:YES];
        [hub show:YES];
        // 如果成功返回数据
        // 接收数据
        NSDictionary *resultDic = result;
        
        NSArray *worksArr = resultDic[@"works"];
        for (NSDictionary *tempDic in worksArr) {
            labelRecommendDetailModel *model = [[labelRecommendDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            [self.packageInfoArr addObject:model];
            
            
        }
        
        
        // 数据加载成功之后,隐藏小菊花
        [self.packageCollectionView reloadData];
        
//        NSLog(@"gggg%ld", self.packageInfoArr.count);
        [hub hide:YES];
    } failure:^(NSError *error) {
        
    }];
}
// 解析案例数据
- (void)createDataCase {

    
    NSString *urlStr = @"http://www.hunliji.com/p/wedding/index.php/home/APIMerchant/WorkList?city=0&sort%5Bkey%5D=created_at&sort%5Border%5D=null&commodity_type=1&mark=999999&per_page=20&page=1";
    
    if (self.index == 0 || self.index == 5) {
        
        // 替换
        self.caseUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
    } else {
        
        self.caseUrlStr = [urlStr stringByReplacingOccurrencesOfString:@"created_at" withString:@"default"];
        self.caseUrlStr = [self.caseUrlStr stringByReplacingOccurrencesOfString:@"999999" withString:[self.ID stringValue]];
        self.caseUrlStr = [self.caseUrlStr stringByReplacingOccurrencesOfString:@"null" withString:@"desc"];
    }
    
    [NetworkTool get:self.caseUrlStr body:nil httpResult:JSON success:^(id result) {
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.caseCollectionVeiw animated:YES];
        [hub show:YES];
        // 如果成功返回数据
        // 接收数据
        NSDictionary *resultDic = result;
        
        NSArray *worksArr = resultDic[@"works"];
        for (NSDictionary *tempDic in worksArr) {
            labelRecommendDetailModel *model = [[labelRecommendDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:tempDic];
            
            [self.caseInfoArr addObject:model];
        }
        
        
        // 数据加载成功之后,隐藏小菊花
        
        [self.caseCollectionVeiw reloadData];
        //        NSLog(@"gggg%ld", self.packageInfoArr.count);
        [hub hide:YES];
    } failure:^(NSError *error) {
        
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)valueChanged:(id)sender
{
    CCSegmentedControl* segmentedControl = sender;
    NSLog(@"%s line:%d segment has changed to %ld", __FUNCTION__, __LINE__, (long)segmentedControl.selectedSegmentIndex);
}

- (UIColor *) colorWithHexString: (NSString *) hexString {
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
    CGFloat alpha, red, blue, green;
    switch ([colorString length]) {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 1];
            green = [self colorComponentFrom: colorString start: 1 length: 1];
            blue  = [self colorComponentFrom: colorString start: 2 length: 1];
            break;
        case 4: // #ARGB
            alpha = [self colorComponentFrom: colorString start: 0 length: 1];
            red   = [self colorComponentFrom: colorString start: 1 length: 1];
            green = [self colorComponentFrom: colorString start: 2 length: 1];
            blue  = [self colorComponentFrom: colorString start: 3 length: 1];
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = [self colorComponentFrom: colorString start: 0 length: 2];
            green = [self colorComponentFrom: colorString start: 2 length: 2];
            blue  = [self colorComponentFrom: colorString start: 4 length: 2];
            break;
        case 8: // #AARRGGBB
            alpha = [self colorComponentFrom: colorString start: 0 length: 2];
            red   = [self colorComponentFrom: colorString start: 2 length: 2];
            green = [self colorComponentFrom: colorString start: 4 length: 2];
            blue  = [self colorComponentFrom: colorString start: 6 length: 2];
            break;
        default:
            [NSException raise:@"Invalid color value" format: @"Color value %@ is invalid.  It should be a hex value of the form #RBG, #ARGB, #RRGGBB, or #AARRGGBB", hexString];
            break;
    }
    return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}

- (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
    NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
    NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
    unsigned hexComponent;
    [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
    return hexComponent / 255.0;
}

@end
